package com.losl.common.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware, BeanFactoryPostProcessor {
    private static ApplicationContext context;

    private static BeanFactory beanFactory;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.context = applicationContext;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        SpringUtils.beanFactory = configurableListableBeanFactory;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName)throws BeansException{
        return (T) beanFactory.getBean(beanName);
    }

    public static <T> T getBean(Class<T> aclass)throws BeansException{
        return (T) beanFactory.getBean(aclass);
    }

    public static boolean contains(String beanName){
        return beanFactory.containsBean(beanName);
    }

}
